package com.lry.basic.nio.mapped;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class FrameIndexFile implements IndexFile<Frame>{

    //id,读指针offset
    private Map<Integer,Integer> indexMap = new HashMap();

    @Override
    public int calWritePos(ByteBuffer buf) {
        int writePos = 0;
        while(buf.hasRemaining()){
            byte start = buf.get();
            if(start!=0x10)
                break;
            writePos++;
            writePos+=4;
            int id = buf.getInt();
            indexMap.put(id,buf.position()-5);
            writePos+=4;
            int len = buf.getInt();
            writePos+=len;
            byte [] msgBytes = new byte[len];
            buf.get(msgBytes);
            String msg = new String(msgBytes);
            writePos++;
            byte end = buf.get();
        }
        return writePos;
    }

    @Override
    public byte[] toBytes(Frame frame,int pos) {
        assert null!=frame;
        int id = frame.getId();
        if(null!=indexMap.get(id)){
            log.info("不可以更新，只能插入数据");
            return null;
        }
        //加入索引
        indexMap.put(id,pos);
        return frame.toBytes();
    }


    @Override
    public Frame get(int id,ByteBuffer buf) {
        //从索引快速获得读指针
        Integer readPos = indexMap.get(id);
        if (null == readPos)
            return null;
        buf.position(readPos);
        //读取一个frame
        if (buf.hasRemaining()) {
            byte start = buf.get();
            if (start != 0x10)
                return null;
            id = buf.getInt();
            int len = buf.getInt();
            byte[] msgBytes = new byte[len];
            buf.get(msgBytes);
            String msg = new String(msgBytes);
            byte end = buf.get();
            return new Frame(start, id, len, msg, end);
        }
        return null;
    }
}
